//
//  BulkOrderViewController.m
//  YYZB
//
//  Created by Tongqingqing on 2017/9/21.
//
//

#import "BulkOrderViewController.h"
#import "ThemeColor.h"
#import "GTIDropDownMenu.h"
#import <MJRefresh/MJRefresh.h>
#import <Masonry/Masonry.h>
#import "GTIDropDownMenuRecord.h"
#import "BulkOrderCell.h"
#import "GroupOrderService.h"
#import "UserInfoController.h"
#import "GroupProject.h"
#import "SVPullToRefresh.h"
#import "ClientWebViewController.h"
#define kDropDownMenuHeight     45

@interface BulkOrderViewController ()<GTIDropDownMenuDataSource, GTIDropDownMenuDelegate,UITableViewDataSource,UITableViewDelegate>

@property (nonatomic, strong) GroupOrderService *groupOrderService;
@property (nonatomic, strong) NSString *sortType;
@property (nonatomic, assign) NSInteger pageSize;
@property (nonatomic, assign) NSInteger pageIndex;
@property (nonatomic, strong) NSArray<GroupProject *> *items;
@property (nonatomic, strong) UIView *bottomView;


@end

@implementation BulkOrderViewController


- (void)viewDidLoad
{
    [super viewDidLoad];
    
//    self.title = @"团购列表";
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.pageSize = 10;
    self.pageIndex = 1;
    self.sortType = @"0";
    [self createTableView];
    [self setUpBottomView];
    [self layoutViews];
    [self addDropDownMenu];
//    [self addRefreshFunction];
//    [self addLoadMoreFunction];
    [self getGroupBuyList:NO];
    [self setupInfiniteScrolling];

}

- (void)createTableView
{
    self.tableView = [[UITableView alloc]initWithFrame:self.view.frame style:UITableViewStyleGrouped];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    self.tableView.backgroundColor = [UIColor clearColor];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
}

//暂时不显示
-(void)setUpBottomView{

    _bottomView = [[UIView alloc]initWithFrame:CGRectMake(0, ScreenHeight-64-40, ScreenWidth, 40)];
    _bottomView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_bottomView];
    
    UILabel *lineLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 1)];
    lineLabel.backgroundColor = [UIColor lightGrayColor];
    [_bottomView addSubview:lineLabel];
    
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(5, 5, _bottomView.width-5, 30)];
    label.text = @"*所有团购商品(团购单品数量超过1个)均可以分次预约上门服务";
    label.font = Font(12);
    [_bottomView addSubview:label];
}
- (void)layoutViews
{
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.mas_topLayoutGuide).offset(kDropDownMenuHeight);
        make.left.right.equalTo(self.view);
        make.bottom.equalTo(self.mas_bottomLayoutGuide);
    }];
}


- (void)setupInfiniteScrolling {
    
    __weak typeof(self) weakSelf = self;
    [self.tableView addInfiniteScrollingWithActionHandler:^{
        [weakSelf loadMoreInfos];
    }];
}

- (void)loadMoreInfos {
    [self getGroupBuyList:YES];
}

//请求
-(void)getGroupBuyList:(BOOL)flag {
    if (!flag) {
        self.pageIndex = 1;
    }
    //sortTyoe：1--价格排序（从低到高） 2--价格排序（从高到低）3--评价排序（从少到多）4--单品数量（从多到少）5--评价优先
    [LoadingView show];
    [self.groupOrderService GetGroupBuyCommunitiesDetailListSortType:self.sortType    pageIndex:@(self.pageIndex) pageSize:@(self.pageSize)   communityId:[UserInfoController defaultCommunityID]  groupBuyingId:self.groupBuyingId completionHanlder:^(NSArray *items, NSError *error) {
        
        [LoadingView dismiss];
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView.infiniteScrollingView stopAnimating];
        });
        if (error) {
            [LoadingView showToast:[error localizedDescription]];
        } else {
            NSMutableArray<GroupProject *> *ps = NSMutableArray.new;
            for (NSDictionary *i in items) {
                [ps addObject:[[GroupProject alloc] initWithDictionary:i]];
            }
            if (flag) {
                self.items = [[self.items arrayByAddingObjectsFromArray:ps] mutableCopy];
            } else {
                self.items = ps;
            }
            self.pageIndex ++;
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
//            self.noDataView.hidden = self.items.count;
        });
        
     
    }];
    
    

}

//#pragma mark AddTableViewPlugin
//- (void)addRefreshFunction
//{
//    // 设置回调（一旦进入刷新状态，就调用target的action，也就是调用self的loadNewData方法）
//    MJRefreshNormalHeader *header = [MJRefreshNormalHeader
//                                     headerWithRefreshingTarget:self
//                                     refreshingAction:@selector(refreshAction)];
//    
//    // 隐藏时间
//    header.lastUpdatedTimeLabel.hidden = YES;
//    
//    // 马上进入刷新状态
//    //    [header beginRefreshing];
//    
//    // 设置header
//    self.tableView.mj_header = header;
//}
//
//- (void)addLoadMoreFunction
//{
//    MJRefreshAutoStateFooter *footer = [MJRefreshAutoStateFooter
//                                        footerWithRefreshingTarget:self
//                                        refreshingAction:@selector(loadMoreAction)];
//    // 设置footer
//    self.tableView.mj_footer = footer;
//    self.tableView.mj_footer.automaticallyHidden = YES;
//}
//#pragma mark RefreshAction
//- (void)refreshAction
//{
//    
//}
//
//- (void)loadMoreAction
//{
//    
//}

- (void)addDropDownMenu
{
    self.dropDownMenu = [[GTIDropDownMenu alloc] initWithOrigin:CGPointMake(0, 0) andHeight:kDropDownMenuHeight];
    self.dropDownMenu.indicatorColor = [UIColor colorWithRed:175.0f/255.0f green:175.0f/255.0f blue:175.0f/255.0f alpha:1.0];
    self.dropDownMenu.separatorColor = [UIColor colorWithRed:210.0f/255.0f green:210.0f/255.0f blue:210.0f/255.0f alpha:1.0];
    self.dropDownMenu.textColor = [UIColor colorWithRed:83.f/255.0f green:83.f/255.0f blue:83.f/255.0f alpha:1.0f];
    self.dropDownMenu.dataSource = self;
    self.dropDownMenu.delegate = self;
    [self.view addSubview:self.dropDownMenu];
}

#pragma mark TableViewDatasource
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [BulkOrderCell cellHeight];
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{

    return 0.0001;

}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.items.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"TableViewCell";
    
    BulkOrderCell* cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if (cell == nil) {
        cell = [[BulkOrderCell alloc]initWithStyle:UITableViewCellStyleDefault
                                     reuseIdentifier:CellIdentifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.backgroundColor = [UIColor clearColor];
    }
    cell.button.tag = 1000 + indexPath.row;
    cell.control.tag = 2000 + indexPath.row;
    GroupProject *p = self.items[indexPath.row];
    [cell fillData:p];
    
    cell.detailBlock = ^(NSString *str, NSInteger tag) {
     
        GroupProject *model = self.items[tag-1000];
        if ([str isEqualToString:@"立即预约"]) {
            ClientWebViewController *webViewController = ClientWebViewController.new;
            webViewController.HTMLURL = [NSString stringWithFormat:@"../projects/projectDetail.html?id=%@&pid=%@&cate1Id=%@", model.ID, model.priceId, model.scat1Id];
            webViewController.title = @"项目详情";
            [self.navigationController pushViewController:webViewController animated:YES];
            
        }else if([str isEqualToString:@"立即购买"]) {
            
            //团购产品只传id
            NSString *url = model.isGroupBuy == 0 ? [NSString stringWithFormat:@"../projects/projectDetail.html?id=%@&pid=%@&cate1Id=%@", model.ID, model.priceId, model.scat1Id] : [NSString stringWithFormat:@"../groupbuy/payingOnline.html?id=%@", model.ID];

            ClientWebViewController *webViewController = ClientWebViewController.new;
            webViewController.HTMLURL = url;
            webViewController.title = @"项目详情";
            [self.navigationController pushViewController:webViewController animated:YES];
            
        }
        
    };
    
    
    cell.detailControlBlock = ^(NSString *str, NSInteger tag) {
        if([str isEqualToString:@"立即购买"]) {
            
            GroupProject *model = self.items[tag-2000];
            NSString *url = model.isGroupBuy == 0 ? [NSString stringWithFormat:@"../projects/projectDetail.html?id=%@&pid=%@&cate1Id=%@", model.ID, model.priceId, model.scat1Id] : [NSString stringWithFormat:@"../groupbuy/payingOnline.html?id=%@", model.ID];
            
            ClientWebViewController *webViewController = ClientWebViewController.new;
            webViewController.HTMLURL = url;
            webViewController.title = @"项目详情";
            [self.navigationController pushViewController:webViewController animated:YES];
            
        }

    };
   
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    GroupProject *model = self.items[indexPath.row];
    
    if (model.remainAmount > 0) {
        NSString *url = model.isGroupBuy == 0 ? [NSString stringWithFormat:@"../projects/projectDetail.html?id=%@&pid=%@&cate1Id=%@", model.ID, model.priceId, model.scat1Id] : [NSString stringWithFormat:@"../groupbuy/groupProjectDetail.html?id=%@", model.ID];
        
        ClientWebViewController *webViewController = ClientWebViewController.new;
        webViewController.HTMLURL = url;
        webViewController.title = @"项目详情";
        [self.navigationController pushViewController:webViewController animated:YES];
    }
    
}

#pragma mark- GTIDropDownMenu DataSource
- (NSInteger)numberOfColumnsInMenu:(GTIDropDownMenu *)menu
{
    return [self.dropDownMenuData count];
}

- (BOOL)displayByCollectionViewInColumn:(NSInteger)column
{
    return NO;
}

- (BOOL)haveRightTableViewInColumn:(NSInteger)column
{
    return NO;
}

- (CGFloat)widthRatioOfLeftColumn:(NSInteger)column
{
    return 1;
}

- (NSInteger)currentLeftSelectedRow:(NSInteger)column
{
    return [self.dropDownMenuSelectedIndex[column] integerValue];
}

- (NSInteger)menu:(GTIDropDownMenu *)menu
numberOfRowsInColumn:(NSInteger)column
      leftOrRight:(NSInteger)leftOrRight
          leftRow:(NSInteger)leftRow
{
    return [self.dropDownMenuData[column] count];
}

- (NSString *)menu:(GTIDropDownMenu *)menu titleForColumn:(NSInteger)column
{
    if ([self.dropDownMenuData[column] count] > 0) {
        GTIDropDownMenuRecord *record = self.dropDownMenuData[column][0];
        if ([record.dataDictionaryDisplayName isEqualToString:@"默认"]) {
            return record.ColDisplayName;
        }
        return record.dataDictionaryDisplayName;
    }
    return nil;
}

- (NSString *)menu:(GTIDropDownMenu *)menu titleForColumnWhenClickedAtIndexPath:(GTIIndexPath *)indexPath
{
    if ([self.dropDownMenuData[indexPath.column] count] > 0) {
        GTIDropDownMenuRecord *record = self.dropDownMenuData[indexPath.column][indexPath.row];
        if ([record.dataDictionaryDisplayName isEqualToString:@"默认"]) {
            return record.ColDisplayName;
        }else if ([record.dataDictionaryDisplayName isEqualToString:@"从低到高"]){
            self.sortType = @"1";
        }else if ([record.dataDictionaryDisplayName isEqualToString:@"从高到低"]){
            self.sortType = @"2";
        }else if ([record.dataDictionaryDisplayName isEqualToString:@"从少到多"]){
            self.sortType = @"3";
        }else if ([record.dataDictionaryDisplayName isEqualToString:@"从多到少"]){
            self.sortType = @"4";
        }else if ([record.dataDictionaryDisplayName isEqualToString:@"销量优先"]){
            self.sortType = @"5";
        }
        return record.dataDictionaryDisplayName;
    }
    return nil;
}

- (NSString *)menu:(GTIDropDownMenu *)menu titleForRowAtIndexPath:(GTIIndexPath *)indexPath
{
    if ([self.dropDownMenuData[indexPath.column] count] > 0) {
        GTIDropDownMenuRecord *record = self.dropDownMenuData[indexPath.column][indexPath.row];
        return record.dataDictionaryDisplayName;
    }
    return nil;
}

#pragma mark- GTIDropDownMenu Delegate
- (void)menu:(GTIDropDownMenu *)menu didSelectRowAtIndexPath:(GTIIndexPath *)indexPath
{
    [self.dropDownMenuData enumerateObjectsUsingBlock:^(NSMutableArray *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (idx != indexPath.column && [self.dropDownMenuSelectedIndex[idx] integerValue] != 0) {
            self.dropDownMenuSelectedIndex[idx] = @0;
//            GTIIndexPath *index = [[GTIIndexPath alloc] initWithColumn:idx leftOrRight:0 leftRow:0 row:0];
//            [self.dropDownMenu.dataSource menu:self.dropDownMenu titleForColumnWhenClickedAtIndexPath:index];
//            [self.dropDownMenu.dataSource menu:self.dropDownMenu titleForColumn:idx];
        }
    }];
    self.dropDownMenuSelectedIndex[indexPath.column] = @(indexPath.row);
    [self.dropDownMenu reloadInputViews];
    
    [self getGroupBuyList:NO];
    
    NSMutableArray *arr = [NSMutableArray arrayWithObjects:@"0",@"1",@"2", nil];
    [arr removeObject:[NSString stringWithFormat:@"%ld",indexPath.column]];
    for (NSString *str in arr) {
        [self.dropDownMenu setMenuTitleWithCol:[str integerValue]];
    }
}

#pragma mark - GTIDropDownServicesManagerDelegate
- (void)getPluginInstanceRelationsSuccessed:(NSDictionary *)dic
{
    
}

-(void)getPluginInstanceRelationsFailed:(NSDictionary *)dic
{
    
}

#pragma mark- getter and setter
- (NSMutableArray *)dropDownMenuData
{
    if (!_dropDownMenuData) {
        GTIDropDownMenuRecord *record10 = [[GTIDropDownMenuRecord alloc]init];
        record10.ColDisplayName = @"价格";
        record10.dataDictionaryDisplayName = @"默认";
        
        GTIDropDownMenuRecord *record1 = [[GTIDropDownMenuRecord alloc]init];
        record1.ColDisplayName = @"价格";
        record1.dataDictionaryDisplayName = @"从高到低";
        
        GTIDropDownMenuRecord *record11 = [[GTIDropDownMenuRecord alloc]init];
        record11.ColDisplayName = @"价格";
        record11.dataDictionaryDisplayName = @"从低到高";
        NSMutableArray *array1 = [NSMutableArray arrayWithObjects:record10,record1,record11, nil];
        
        GTIDropDownMenuRecord *record2 = [[GTIDropDownMenuRecord alloc]init];
        record2.ColDisplayName = @"单品数量";
        record2.dataDictionaryDisplayName = @"默认";
        
        GTIDropDownMenuRecord *record20 = [[GTIDropDownMenuRecord alloc]init];
        record20.ColDisplayName = @"单品数量";
        record20.dataDictionaryDisplayName = @"从多到少";
        
        GTIDropDownMenuRecord *record21 = [[GTIDropDownMenuRecord alloc]init];
        record21.ColDisplayName = @"单品数量";
        record21.dataDictionaryDisplayName = @"从少到多";
        
        NSMutableArray *array2 = [NSMutableArray arrayWithObjects:record2,record20,record21, nil];
        
        GTIDropDownMenuRecord *record3 = [[GTIDropDownMenuRecord alloc]init];
        record3.ColDisplayName = @"销量优先";
        record3.dataDictionaryDisplayName = @"销量优先";
        NSMutableArray *array3 = [NSMutableArray arrayWithObjects:record3, nil];
        
        _dropDownMenuData = [NSMutableArray arrayWithObjects:array1, array2, array3, nil];
    }
    return _dropDownMenuData;
}

- (NSMutableArray *)dropDownMenuSelectedIndex
{
    if (!_dropDownMenuSelectedIndex) {
        _dropDownMenuSelectedIndex = [NSMutableArray arrayWithObjects:@0, @0, @0, nil];
    }
    return _dropDownMenuSelectedIndex;
}



-(GroupOrderService *)groupOrderService{
    if (!_groupOrderService) {
        _groupOrderService = GroupOrderService.new;
    }
    return _groupOrderService;
}


@end
